package com.wrx.club_management_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.dto.UserDTO;
import com.wrx.club_management_backend.entity.Comment;
import com.wrx.club_management_backend.mapper.CommentMapper;
import com.wrx.club_management_backend.service.CommentService;
import com.wrx.club_management_backend.utils.UserHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Override
    public AjaxResult push(Comment comment) {
        try {
            UserDTO user = UserHolder.getUser();
            Long userId = user.getId();
            comment.setId(userId);
            String avatar = user.getAvatar();
            comment.setAvatar(avatar);
            String nickname = user.getNickname();
            comment.setNickname(nickname);
            this.save(comment);
            return AjaxResult.success("评论成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("评论失败");
        }
    }
    /**
     * 根据 newsid 获取所有的评论包括二级评论
     * @param newsId 动态id
     * @return 评论列表
     */
    @Override
    public List<Comment> getComments(Long newsId) {
        //1. 查询该动态的所有根评论
        List<Comment> list = this.list(
                new LambdaQueryWrapper<Comment>()
                        .eq(Comment::getNewsId, newsId)
                        .eq(Comment::getIsRoot, 1)
        );
        //2. 查询所有评论的子评论
        list.forEach(
                item -> {
                    Long commentId = item.getId();
                    List<Comment> replies = this.list(
                            new LambdaQueryWrapper<Comment>()
                                    .eq(Comment::getNewsId, newsId)
                                    .eq(Comment::getIsRoot, 0)
                                    .eq(Comment::getParentId, commentId)
                    );
                    item.setReplies(replies);
                }
        );
        //3. 返回数据
        return list;
    }
}
